package fragment;

import android.app.ActionBar;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.mywood.LoginActivity;
import com.example.mywood.R;
import com.example.mywood.SearchActivity;
import com.example.mywood.ZhantingGoodsActivity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import adapter.ListviewAdapter;
import adapter.ShaixuanAllAdapter;
import bean.ContentDataBean;
import bean.ShowRoomAllDataBean;
import bean.ZhantingListBean;
import myapp.MyApp;
import util.DensityUtil;
import util.GlideUtils;
import util.MyLog;
import util.OrderEventMessage;
import util.RequestManager;

public class ZhantingFragment2 extends Fragment {

    private View view;
    private Context mcontext;
    private LinearLayout ll_nodata;
    private LinearLayout ll_data;
    private LinearLayout ll_search;
    private LinearLayout ll_zhanting;
    private TextView tv_zhanting;
    private MyApp myapp;
    private String token;
    private List<ZhantingListBean.DataBean> temzhantingList = new ArrayList<>();
    private PopupWindow mPopupWindow;
    private int heightPixels;
    private ShaixuanAllAdapter sadapter;
    private TextView tv_zhanting_name;
    private WebView tv_content;
    private TextView tv_phone;
    private TextView tv_time;
    private TextView tv_location;
    private String nameStr;
    private String phoneStr;
    private String imageStr;
    private String start_timeStr;
    private String end_timeStr;
    private String contentStr;
    private String locationStr;
    private ImageView img;
    private LinearLayout ll_zhantinggoods;
    private LinearLayout ll_location;

    private PackageManager mPackageManager;
    private static List<String> mPackageNames = new ArrayList<>();
    private static final String GAODE_PACKAGE_NAME = "com.autonavi.minimap";
    private static final String BAIDU_PACKAGE_NAME = "com.baidu.BaiduMap";
private double currLocationX = 0.0;
private double currLocationY = 0.0;
private double locationX = 0.0;
private double locationY = 0.0;
private String storeName = "北京饭店";

//    private double currLocationX;//起点 纬度
//    private double currLocationY;//起点 经度
//    private double locationX;//终点 纬度
//    private double locationY;//终点 经度
//    private String storeName;//地点名称
    private String url;
    private String apptype = "";
    private String textData;
    private SharedPreferences sharedPreferences;
    private LinearLayout ll_dataall;
    private ListView listview;
    private List<ShowRoomAllDataBean> alldatalist = new ArrayList<>();
    private ListviewAdapter allDataAdapter;
    private ContentDataBean.DataBean textContent;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        MyLog.e("Activity:", this.getClass().getName().toString());
        view = inflater.inflate(R.layout.fragment_zhanting, container, false);
        mcontext = getActivity();
        myapp = (MyApp) mcontext.getApplicationContext();
        getScreenDen();
        sharedPreferences = mcontext.getSharedPreferences("userInfo", Context.MODE_PRIVATE);
        token = sharedPreferences.getString("token", "");
        apptype = sharedPreferences.getString("apptype", "0");
        textData = sharedPreferences.getString("textData", "");
        mPackageManager = mcontext.getPackageManager();
        EventBus.getDefault().register(this);
        initView();
        initLin();
        getAllData();
//        getZhantingListData();

        return view;

    }
    @Subscribe
    public void onEventMainThread(OrderEventMessage event) {
        String message = event.getMessage();
        MyLog.e("message--new--order", message);
        if ("跳转地图导航".equals(message)) {
            locationStr = event.getType();
            MyLog.e("type--new--order", locationStr);
            if(haveGaodeMap()){//如果安装高德APP
                openGaodeMapToGuide();//打开高德APP
            } else {//否则 打开浏览器
                openBrowserToGuide();
            }
        }else if ("跳转商品链接".equals(message)){
            String type = event.getType();
            MyLog.e("name--new--order", type);
            Intent intent = new Intent(mcontext, ZhantingGoodsActivity.class);
            intent.putExtra("ztname",type);
            startActivity(intent);
        }

    }
    private void initView() {
        textContent = new Gson().fromJson(textData, new TypeToken<ContentDataBean.DataBean>() {}.getType());
        listview = view.findViewById(R.id.listview);
        allDataAdapter = new ListviewAdapter(alldatalist,mcontext,myapp, textContent);
        listview.setAdapter(allDataAdapter);
        ll_dataall = view.findViewById(R.id.ll_dataall);
        ll_data = view.findViewById(R.id.ll_data);
        ll_nodata = view.findViewById(R.id.ll_nodata);
        ll_search = view.findViewById(R.id.ll_search);
        ll_zhanting = view.findViewById(R.id.ll_zhanting);
        tv_zhanting = view.findViewById(R.id.tv_zhanting);
        tv_zhanting_name = view.findViewById(R.id.tv_zhanting_name);
        tv_content = view.findViewById(R.id.tv_content);
        tv_phone = view.findViewById(R.id.tv_phone);
        tv_time = view.findViewById(R.id.tv_time);
        tv_location = view.findViewById(R.id.tv_location);
        img = view.findViewById(R.id.img);
        ll_zhantinggoods = view.findViewById(R.id.ll_zhantinggoods);
        ll_location = view.findViewById(R.id.ll_location);
        sadapter = new ShaixuanAllAdapter(mcontext, temzhantingList);

        TextView tv_title = view.findViewById(R.id.tv_title);
        TextView tv_shou_phone = view.findViewById(R.id.tv_shou_phone);
        TextView tv_opentime = view.findViewById(R.id.tv_opentime);
        TextView tv_address = view.findViewById(R.id.tv_address);
        TextView tv_goods_link = view.findViewById(R.id.tv_goods_link);
        TextView tv_nodata = view.findViewById(R.id.tv_nodata);
        if (textContent != null){
            tv_title.setText(textContent.getShowroom());
            tv_zhanting.setText(textContent.getSelect_showroom());
            tv_shou_phone.setText(textContent.getSale_phone());
            tv_opentime.setText(textContent.getBusiness_hours());
            tv_address.setText(textContent.getAddress_sign());
            tv_goods_link.setText(textContent.getRecome_good_link());
            tv_nodata.setText(textContent.getNodata());
        }

    }

    private void initLin() {
        ll_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(mcontext, SearchActivity.class);
                intent.putExtra("activityType","");
                intent.putExtra("showroom","");
                startActivity(intent);
            }
        });
        ll_zhanting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                initunitbyWindow();
            }
        });
        ll_zhantinggoods.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(mcontext, ZhantingGoodsActivity.class);
                intent.putExtra("ztname",nameStr);
                startActivity(intent);
            }
        });
        ll_location.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(haveGaodeMap()){//如果安装高德APP
                    openGaodeMapToGuide();//打开高德APP
                } else {//否则 打开浏览器
                    openBrowserToGuide();
                }

            }
        });
    }

      int checkid = 0;
    /**
     * 弹出单个筛选框
     */
    private void initunitbyWindow() {
        LayoutInflater layoutInflater = LayoutInflater.from(mcontext);
        View popupWindow = layoutInflater.inflate(R.layout.popup_shaixuan, null);
        ListView listview = popupWindow.findViewById(R.id.listview);
        View viewById = popupWindow.findViewById(R.id.view_zhezhao);
        View view_line = popupWindow.findViewById(R.id.view_line);
        LinearLayout ll_button = popupWindow.findViewById(R.id.ll_button);
        view_line.setVisibility(View.GONE);
        ll_button.setVisibility(View.GONE);
        viewById.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPopupWindow.dismiss();
            }
        });

        if (sadapter != null){
            listview.setAdapter(sadapter);
            sadapter.setData(temzhantingList, checkid);

        }


        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                checkid = i;
                sadapter.setData(temzhantingList, i);
                int id = temzhantingList.get(i).getId();
                String zhanname = temzhantingList.get(i).getName();
                tv_zhanting.setText(zhanname);
                getZhantingData(id+"");
            }
        });


        int mScreenWidth = getActivity().getWindowManager().getDefaultDisplay().getWidth();
        mPopupWindow = new PopupWindow(popupWindow, ActionBar.LayoutParams.FILL_PARENT,
                ActionBar.LayoutParams.WRAP_CONTENT);
        mScreenWidth = getActivity().getWindowManager().getDefaultDisplay().getHeight();
        int mPopupWindowWidth = mPopupWindow.getWidth();
        int mPopupWindowHeight = mPopupWindow.getHeight();
        // 需要设置一下此参数，点击外边可消失
        mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
        mPopupWindow.setOutsideTouchable(true);
        mPopupWindow.setTouchable(true);
        mPopupWindow.setFocusable(true); // pop 显示时， 不让外部 view 响应点击事件

        if (Build.VERSION.SDK_INT >= 24) { // Android 7.x中,PopupWindow高度为match_parent时,会出现兼容性问题,需要处理兼容性
            int offsetY = DensityUtil.dip2px(mcontext, 112);
            if (Build.VERSION.SDK_INT >= 25) { // Android 7.1中，PopupWindow高度为 match_parent 时，会占据整个屏幕
                //故而需要在 Android 7.1上再做特殊处理
                int screenHeight = heightPixels; // 获取屏幕高度
//                int screenHeight = DisplayUtil.getScreenHeight(MainActivity.this); // 获取屏幕高度
                mPopupWindow.setHeight(screenHeight - offsetY); // 重新设置 PopupWindow 的高度
            }
            mPopupWindow.showAtLocation(ll_zhanting, Gravity.NO_GRAVITY, 0, offsetY);
        } else {
            mPopupWindow.showAsDropDown(ll_zhanting);
        }

        mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {

            }
        });

    }


    /**
     * 请求头部筛选标题
     */
    private void getZhantingListData() {
        temzhantingList.clear();
        String url = myapp.getWebConfig() + "/api/index/gallery_list";
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("token", token);
        paramsMap.put("is_material", apptype);
        RequestManager.getInstance(mcontext).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {

                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 0;
                        handler.sendMessage(msg);
                        return;
                    }
                    JSONArray data = jsonObject.getJSONArray("data");
                    temzhantingList = new Gson().fromJson(data.toString(), new TypeToken<List<ZhantingListBean.DataBean>>() {
                    }.getType());


                    msg.arg1 = 2;
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                MyLog.e("result", errorMsg);
                if (errorMsg.equals("未登录")){
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                }
            }
        });
    }
    /**
     * 请求头部筛选标题
     */
    private void getZhantingData(String id) {
        String url = myapp.getWebConfig() + "/api/index/gallery_detail";
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("token", token);
        paramsMap.put("gallery_id", id);
        paramsMap.put("is_material", apptype);
        RequestManager.getInstance(mcontext).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {

                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 0;
                        handler.sendMessage(msg);
                        return;
                    }
                    JSONObject data = jsonObject.getJSONObject("data");
                    nameStr = data.getString("name");
                    phoneStr = data.getString("phone");
                    imageStr = data.getString("image");
                    start_timeStr = data.getString("start_time");
                    end_timeStr = data.getString("end_time");
                    contentStr = data.getString("content");
//                    locationStr = data.getString("location");


                    msg.arg1 = 3;
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                MyLog.e("result", errorMsg);
                if (errorMsg.equals("未登录")){
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                }
            }
        });
    }

    /**
     * 请求头部筛选标题
     */
    private void getAllData() {
        alldatalist.clear();
        String url = myapp.getWebConfig() + "/api/index/exhibition";
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("token", token);
//        paramsMap.put("gallery_id", id);
//        paramsMap.put("is_material", apptype);
        RequestManager.getInstance(mcontext).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {

                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 0;
                        handler.sendMessage(msg);
                        return;
                    }
                    JSONArray data = jsonObject.getJSONArray("data");
                    for (int i = 0;i<data.length();i++){
                        ShowRoomAllDataBean bean = new ShowRoomAllDataBean();

                        bean.setId(data.getJSONObject(i).getString("id"));
                        bean.setContent(data.getJSONObject(i).getString("content"));
                        bean.setName(data.getJSONObject(i).getString("name"));
                        bean.setName_tran(data.getJSONObject(i).getString("name_tran"));
                        bean.setPhone(data.getJSONObject(i).getString("phone"));
                        bean.setWeigh(data.getJSONObject(i).getString("weigh"));
                        bean.setImage(data.getJSONObject(i).getString("image"));
                        bean.setStart_time(data.getJSONObject(i).getString("start_time"));
                        bean.setEnd_time(data.getJSONObject(i).getString("end_time"));
                        bean.setContent_tran(data.getJSONObject(i).getString("content_tran"));
                        bean.setLocation(data.getJSONObject(i).getString("location"));
                        bean.setLocation_tran(data.getJSONObject(i).getString("location_tran"));
                        bean.setKind_item_id(data.getJSONObject(i).getString("kind_item_id"));
                        bean.setUpdatetime(data.getJSONObject(i).getString("updatetime"));
                        bean.setCreatetime(data.getJSONObject(i).getString("createtime"));
                        alldatalist.add(bean);
                    }



                    msg.arg1 = 5;
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                MyLog.e("result", errorMsg);
                if (errorMsg.equals("未登录")){
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                }
            }
        });
    }

    public Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.arg1) {
                case 0:
                    String str = (String) msg.obj;
                    Toast.makeText(mcontext, str, Toast.LENGTH_LONG).show();
                    if (str.contains("当前展厅不存在")){
                        ll_nodata.setVisibility(View.VISIBLE);
                        ll_data.setVisibility(View.GONE);
                    }
                    break;
                case 1:
                    Toast.makeText(mcontext, textContent.getNet_error(), Toast.LENGTH_LONG).show();
                    break;
                case 2:
                    if (mPopupWindow != null) {
                        mPopupWindow.dismiss();
                    }
                    if (temzhantingList.size() > 0){
                        String zhanname = temzhantingList.get(0).getName();
                        tv_zhanting.setText(zhanname);
                        getZhantingData(temzhantingList.get(0).getId()+"");
                    }else{
                        ll_nodata.setVisibility(View.VISIBLE);
                        ll_data.setVisibility(View.GONE);
                    }

                    break;
                case 3:
                    if (mPopupWindow != null) {
                        mPopupWindow.dismiss();
                    }
                    ll_nodata.setVisibility(View.GONE);
                    ll_data.setVisibility(View.VISIBLE);
                    tv_zhanting_name.setText(nameStr);
                    tv_phone.setText(phoneStr);
                    tv_time.setText(start_timeStr+"-"+end_timeStr);
                    tv_location.setText(locationStr);
//                    tv_content.setText(contentStr);

                    tv_content.getSettings().setDefaultTextEncodingName("UTF-8");
                    tv_content.loadDataWithBaseURL(null, contentStr+"<style> img{max-width:100%;max-height:100%} </style>", "text/html", "utf-8", null);
                    tv_content.setWebViewClient(new WebViewClient());

                    if (!"".equals(imageStr)){
                        img.setVisibility(View.VISIBLE);
                        GlideUtils.loadRoundCircleImage(mcontext,imageStr,img);
                    }else{
                        img.setVisibility(View.GONE);
                    }

                    break;
                case 4:

                    break;
                case 11:
                    if (!islogin){
                        islogin = true;
                        sharedPreferences.edit().putString("token", "").commit();
                        Intent intent = new Intent(mcontext, LoginActivity.class);
                        mcontext.startActivity(intent);
                        myapp.destoryActivity("主页面");
                    }
                    break;
                case 5:

                    allDataAdapter.setData(alldatalist);
                    break;
            }
        }
    };
private boolean islogin = false;
    /**
     * 获取屏幕宽度
     */
    private void getScreenDen() {

        WindowManager manager = getActivity().getWindowManager();
        DisplayMetrics dm = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(dm);
        //以要素为单位
        int width = dm.widthPixels;
        heightPixels = dm.heightPixels;
        MyLog.e("获取屏幕高度", heightPixels + "    高度");
    }
    @Override
    public void onResume() {
        super.onResume();
        MyLog.e("展厅","onResume");
    }
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        MyLog.e("展厅","onHiddenChanged     "+hidden);
        if (!hidden){
            checkid = 0;
            getZhantingListData();
        }




    }



    /**
     * 打开高德地图
     * https://lbs.amap.com/api/amap-mobile/guide/android/route
     */
    private void openGaodeMapToGuide() {
        try {
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            intent.addCategory(Intent.CATEGORY_DEFAULT);
            MyLog.i("高德定位：","经度："+currLocationY+" ,纬度："+currLocationX);
            if (currLocationX == 0.0 || currLocationY == 0.0){
                url = "androidamap://route?sourceApplication=amap"+"&dname="+locationStr+"&dev=0&t=1";
            }else {
                url = "androidamap://route?sourceApplication=amap&"
                        +"&dname="+locationStr+"&dev=0&t=1";
            }



            Uri uri = Uri.parse(url);
            //将功能Scheme以URI的方式传入data
            intent.setData(uri);
            //启动该页面即可
            startActivity(intent);

        }catch (Exception e){
            openBrowserToGuide();
        }
    }


    /**
     * 打开浏览器
     */
    private void openBrowserToGuide() {
        String url = "http://uri.amap.com/navigation?to=" +
                locationStr + "&mode=car&policy=1&src=mypage&coordinate=gaode&callnative=0";
        Uri uri = Uri.parse(url);
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        startActivity(intent);
    }





    public void initPackageManager(){
        mPackageManager = mcontext.getPackageManager();
        List<PackageInfo> packageInfos = mPackageManager.getInstalledPackages(0);
        if (packageInfos != null) {
            for (int i = 0; i < packageInfos.size(); i++) {
                mPackageNames.add(packageInfos.get(i).packageName);
            }
        }
    }

    /**
     * 判断有无安装高德
     * @return
     */
    public boolean haveGaodeMap(){
        initPackageManager();
        return mPackageNames.contains(GAODE_PACKAGE_NAME);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
